﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using PersonaLibrary.Data;

namespace PersonaLibrary.ViewModel.CleanBD
{
	public class CleanDepartments : BaseViewModel<View.CleanDB>
	{
		private readonly LinqToDbDataContext _context = new LinqToDbDataContext();
		private ObservableCollection<Department> _departments = new ObservableCollection<Department>();
		private BaseEntity _selectedItem;
		private RelayCommand _deleteSelectedItem;
		private RelayCommand _deleteAllItems;

		public CleanDepartments()
		{
			View.Loaded += ViewLoaded;
		}

		void ViewLoaded(object sender, System.Windows.RoutedEventArgs e)
		{
			var departments = _context.Departments.Where(x => x.ConnectionJobEmplDeps.Count == 0);
			Collection = new ObservableCollection<Department>(departments);
			SelectedItem = null;
		}

		private void DeleteSelectedItem(object obj)
		{
			BaseEntity baseEntity = (BaseEntity)obj;
			int id = baseEntity.Id;
			Department job = _context.Departments.FirstOrDefault(x => ((Department)x).Id == id);

			if (job == null)
			{
				MessageBox.Show(string.Format("Не удалось удалить отдел {0} '{1}'", Environment.NewLine, SelectedItem));
				return;
			}

			try
			{
				_context.Departments.DeleteOnSubmit(job);
				_context.SubmitChanges();
				SelectedItem = null;
				Collection.Remove((Department)baseEntity);
			}
			catch (Exception)
			{
				MessageBox.Show("Произошла ошибка при попытке удалить отдела");
			}
		}

		private void DeleteAllItems()
		{
			try
			{
				_context.Departments.DeleteAllOnSubmit(Collection);
				_context.SubmitChanges();
				SelectedItem = null;
				Collection.Clear();
			}
			catch (Exception)
			{
				MessageBox.Show("Произошла ошибка при попытке удалить отделы");
			}
		}

		public RelayCommand DeleteSelectedItemCommand
		{
			get
			{
				if (_deleteSelectedItem == null)
					_deleteSelectedItem = new RelayCommand(x => DeleteSelectedItem(x), x => x is BaseEntity);
				return _deleteSelectedItem;
			}
		}

		public RelayCommand DeleteAllItemsCommand
		{
			get
			{
				if (_deleteAllItems == null)
					_deleteAllItems = new RelayCommand(x => DeleteAllItems(), x => Collection.Count > 0);
				return _deleteAllItems;
			}
		}

		public ObservableCollection<Department> Collection
		{
			get { return _departments; }
			set
			{
				_departments = value;
				RisePropertyChanged("Collection");
			}
		}

		public BaseEntity SelectedItem
		{
			get { return _selectedItem; }
			set
			{
				_selectedItem = value;
				RisePropertyChanged("SelectedItem");
			}
		}
	}
}
